#include "Deferred.fxh"

float3 g_EdgeDetection_Color;
float2 g_EdgeDetection_Params;

void EdgeDetectionPS(in float2 Pos : VPOS, in float3 EyeVec : TEXCOORD0, out float4 Out : COLOR0)
{
	GBUFFER_DATA Data;
	SampleGBuffers(Pos, EyeVec, Data);

	GBUFFER_DATA AroundData[4];
	float2 tex = (Pos - float2(0.5, 0.5)) * g_ScreenSize_Inv;
	float2 texd = g_EdgeDetection_Params.x * g_ScreenSize_Inv;
	SampleGBuffers_Tex(tex+float2(-texd.x, 0), EyeVec, AroundData[0]);
	SampleGBuffers_Tex(tex+float2( texd.x, 0), EyeVec, AroundData[1]);
	SampleGBuffers_Tex(tex+float2(0, -texd.y), EyeVec, AroundData[2]);
	SampleGBuffers_Tex(tex+float2(0,  texd.y), EyeVec, AroundData[3]);
	
	/*float4 DistV = float4(
		AroundData[0].Pos_View.z - AroundData[1].Pos_View.z,
		AroundData[0].Pos_View.z - AroundData[2].Pos_View.z,
		AroundData[1].Pos_View.z - AroundData[3].Pos_View.z,
		AroundData[2].Pos_View.z - AroundData[3].Pos_View.z);*/
	float2 DistV = float2(
		AroundData[0].Pos_View.z + AroundData[1].Pos_View.z - 2 * Data.Pos_View.z,
		AroundData[2].Pos_View.z + AroundData[3].Pos_View.z - 2 * Data.Pos_View.z);
	DistV = abs(DistV)*g_EdgeDetection_Params.y;
	/*float4 NormalV = float4(
		1-dot(AroundData[0].Normal_View, AroundData[1].Normal_View),
		1-dot(AroundData[0].Normal_View, AroundData[2].Normal_View),
		1-dot(AroundData[1].Normal_View, AroundData[3].Normal_View),
		1-dot(AroundData[2].Normal_View, AroundData[3].Normal_View));*/
	float2 NormalV = float2(
		1-dot(AroundData[0].Normal_View, AroundData[1].Normal_View),
		1-dot(AroundData[2].Normal_View, AroundData[3].Normal_View));
	NormalV = abs(NormalV);
	float Edge = dot(DistV, DistV) + dot(NormalV, NormalV);
	Out.rgb = g_EdgeDetection_Color;
	Out.a = saturate(Edge);
}

technique EdgeDetection {
	pass {
		AlphaBlendEnable = true;
		SrcBlend  = SRCALPHA;
		DestBlend = INVSRCALPHA;
		VertexShader = compile vs_3_0 MainVS();
		PixelShader  = compile ps_3_0 EdgeDetectionPS();
	}
}

